import {defineStore} from "pinia";
import {reactive, ref} from "vue";
import axios from "axios";
import baseURL from "@/config/config.js";
import router from "@/router/index.js";
import {ElMessage} from "element-plus";
export const useUserStore = defineStore("userStore", () => {
    const token = ref('')
    const role = ref('')
    const baseInfo = ref({
        "campusId": '',
        "name": '',
        "phone": '',
        "sex": ''
    })

    const student = ref({
        studentId: '',
        classId: '',
        className: '',
        majorId: '',
        majorName: '',
        collegeId: '',
        collegeName: '',
    })

    const teacher = ref({
        teacherId: '',
        collegeId: 1,
        title: '讲师',
        dateOfEntry: '2025-05-29',
        officeAddress: '逸夫楼',
        biography: '从事教育工作10年，主要研究方向为人工智能与机器学习。曾主持多项省级科研项目，发表学术论文20余篇。热爱教学工作，致力于培养学生的创新能力和实践能力。'
    })

    function setData(data, rl) {

        role.value = rl
        if (rl === 'admin'){
            router.push('/admin')
            return
        }
        baseInfo.value = data.info.baseInfo
        if (rl === 'student'){
            student.value.studentId = data.info.studentId
            student.value.classId = data.info.classId
            router.push('/student')
        }else {
            console.log("教师特殊信息：", data.collegeId)
            teacher.value.teacherId = data.info.teacherId
            teacher.value.collegeId = data.info.collegeId
            router.push('/teacher')
        }
    }

    async function getInfoByToken() {
        try {
            const response = await axios({
                url: baseURL + '/user/get-info',
                method: 'get',
                headers: {
                    Authorization: `Bearer ${token.value}`,
                }
            });

            console.log("用户信息：" + JSON.stringify(response.data));
            setData(response.data.data, response.data.data.role);

            return role.value;
        } catch (error) {
            console.error('获取用户信息失败:', error);
            // throw error; // 抛出错误，让调用者处理
        }
    }
    function resetData() {
        token.value = ''
        role.value = ''
        baseInfo.value = {
            "campusId": '',
            "name": '',
            "phone": '',
            "sex": ''
        }
        student.value = {
            studentId: '',
            classId: '',
            className: '',
            majorId: '',
            majorName: '',
            collegeId: '',
            collegeName: '',
        }
        teacher.value = {
            teacherId: '',
            collegeId: 0,
            title: '',
            dateOfEntry: '',
            officeAddress: '',
            biography: ''

        }
    }
    return {
        role,
        baseInfo,
        student,
        teacher,
        setData,
        token,
        getInfoByToken,
        resetData
    }
})